<template>
  <div class="terminal-page">
    <div class="terminal-search-title">
      <el-row :gutter="15">
        <el-col :span="3">
          <el-input
            placeholder="搜索终端名称"
            suffix-icon="el-search"
            @keyup.native.enter="queryMethods"
            v-model="searchObj.name">
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="searchObj.groupId"
            placeholder="组名"
            @change="queryMethods"
            clearable
          >
            <el-option
              v-for="(item, index) in groupList"
              :label="item.group_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-col>

        <el-col class="control-fixed-pos" :span="18">
          <el-button type="default" @click="restartWindows">重启</el-button>
          <el-button type="default" @click="startWindows">开机</el-button>
          <el-button type="default" @click="closeWindows">关机</el-button>
          <el-button type="default" @click="changeDesktops('desktop')">显示桌面</el-button>
          <el-button type="default" @click="changeDesktops('application')">显示应用界面</el-button>
          <el-button type="primary" @click="queryMethods">刷新</el-button>
          <el-button type="primary" @click="addNewTer">添加</el-button>
          <el-button type="danger" @click="mutiDelMethods" icon="el-icon-delete">删除</el-button>
        </el-col>
      </el-row>
    </div>

    <CommonTable
      class="commonTable"
      ref="terminalTableRef"
      :is-selection="true"
      :is-show-index="true"
      :is-has-opera="true"
      row-key="deccaId"
      @changeRow="changeRowMethods"
      :t-column-data="terminalListCol"
      :t-data="terminalList"
      :remote-api="getClientList"
      :is-reserve-select="true"
      operating-width="220px"
    >
      <template slot="operate" slot-scope="scope" class="operate-btn">
        <el-button type="text" @click="editTerInfo(scope.row)">编辑</el-button>
        <el-button type="text" class="del-button" @click="delTerRow(scope.row)">删除</el-button>
<!--        <el-button type="text" @click="goToFilePage(scope.row)">查看文件</el-button>-->
        <img style="margin-right: 10px;" src="./image/folder.png" @click="goToFilePage(scope.row)" class="icon-image" alt="">
        <el-popover
          placement="bottom"
          width="200"
          trigger="hover"
        >
          <div class="menu-list">
            <div class="menu-list-row" @click="closeWindow(scope.row)">
              <img src="./image/close-terminal.png" class="icon-image-inside" alt="">
              <div>关机</div>
            </div>
            <div class="menu-list-row" @click="startWindow(scope.row)" >
              <img src="./image/start.png" class="icon-image-inside" alt="">
              <div>开机</div>
            </div>
            <div class="menu-list-row" @click="restartWindow(scope.row)" >
              <img src="./image/restart.png" class="icon-image-inside" alt="">
              <div>重启</div>
            </div>
            <div class="menu-list-row" @click="changeDesktop(scope.row, 'application')">
              <img src="./image/PC.png" class="icon-image-inside" alt="">
              <div>切换到应用桌面</div>
            </div>
            <div class="menu-list-row" @click="changeDesktop(scope.row, 'desktop')">
              <img src="./image/windows-fill.png" class="icon-image-inside" alt="">
              <div>切换到电脑桌面</div>
            </div>

            <div class="menu-list-row" @click="remoteControl(scope.row)">
              <img src="./image/control.png" class="icon-image-inside" alt="">
              <div>远程控制</div>
            </div>

            <div class="menu-list-row" @click="getCode(scope.row)">
              <img src="./image/scan.png" class="icon-image-inside" alt="">
              <div v-if="scope.row.qrcode == 0">显示二维码</div>
              <div v-if="scope.row.qrcode == 1">关闭二维码</div>
            </div>
          </div>
          <img
            src="./image/other.png"
            slot="reference"
            class="icon-image"
            alt=""
          >

        </el-popover>
      </template>
    </CommonTable>

    <WarnPanelDialog
      :statusProp="statusProp"
      @confirmHandler="confirmDelMethods"
      @cancelHandler="cancelHandler"
    ></WarnPanelDialog>

    <el-dialog
      title="终端信息"
      :visible.sync="showTerDialog"
      width="50%"
      :before-close="handleClose">
      <el-form ref="form" :model="terForm" label-width="80px">
        <el-form-item label="终端名称">
          <el-input v-model.trim="terForm.name"></el-input>
        </el-form-item>
        <el-form-item label="分组">
          <el-select
            v-model="terForm.groupId"
            placeholder="组名"
          >
            <el-option
              v-for="(item, index) in groupList"
              :label="item.group_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirmUploadFile">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加终端"
      :visible.sync="addTerModal"
      width="60%"
      :before-close="handleClose">
      <el-row v-if="addTerModal" :gutter="12">
        <el-form ref="form" :model="terForm" label-width="100px">
          <el-col :span="12">
            <el-form-item label="终端序列号">
              <el-input v-model.trim="terForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="primary">广播搜索</el-button>
            <el-button>批量添加</el-button>
          </el-col>
        </el-form>
      </el-row>

      <CommonTable
        v-if="addTerModal"
        class="commonTable"
        ref="terminalTableRef"
        :is-selection="true"
        :is-show-index="true"
        :is-has-opera="true"
        @changeRow="changeSelectTerRowMethods"
        :t-column-data="terminalListCol"
        :remote-api="getClientList"
        :is-reserve-select="true"
        operating-width="120px"
      >
      </CommonTable>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirmUploadFile">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonTable from "@/components/Table/commonTable";
import {terminalListCol} from './tableCol/terminalListCol'
import {sendCmd} from '../terminalDetail/utils/sendCmd'
import * as service from './service'
import {encrypt,decrypt} from "../../utils/RSA"

export default {
  name: "index",
  components: {
    CommonTable
  },
  data() {
    return {
      terForm: {
        name: '',
        groupId: ''
      },
      showTerDialog: false,
      statusProp: false,
      getClientList: service.getClientList,
      terminalList: [],
      searchObj: {
        name: '',
        groupId: '',
        page: 1,
        pageSize: 20
      },
      terminalListCol,
      total: 0,
      clickCache: {},
      mutiDelList: [],
      groupList: [],
      addTerModal: false,
      perAddSelectTer: [],
      publicKey: null,
    }
  },
  mounted() {
    this.publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALGuzxAlEYSw+xREG+/RfuF0k3yW70Iqz4NJaMYCFQW164/RF3YLnFovuXpjD03OSa11esOOvN9zK60o7yZcrcECAwEAAQ==";
    this.getGroupList()
  },
  methods: {
    getCode(row) {
      let _this = this;
      let qrcode = row.qrcode;
      const clientId = row.id;
      let userInfo = JSON.parse(window.localStorage.getItem('userInfo'))
      const userId = userInfo.id;
      let str = clientId + "&" + userId;
      let obj = null;
      if(qrcode == 0) {
        //显示二维码
        obj = {
          "id": clientId,
          "qrcode": 1
        }
      } else {
        //关闭二维码
        obj = {
          "id": clientId,
          "qrcode": 0
        }
      }
      service.qrcode(obj).then((res) => {
        if(res.code == 200) {
          let dataList = _this.$refs.terminalTableRef.getTableData()
          let index = 0;
          dataList.forEach((item) => {
            if(item.id == clientId) {
              item.qrcode = obj.qrcode;
              _this.$refs.terminalTableRef.setTableDataByIndex(item, index)
            }
            index++;
          })
          let clientDetial = {
            "ip": row.ip
          }
          if(qrcode == 0) {
            //显示二维码
            let params = encrypt(str, this.publicKey);
            let url = "http://10.206.1.124:1024/jzkc/terminal/terminalDetailVertical?p="+params;

            // let url = "http://"+location.host + "/jzkc/terminal/terminalDetailVertical?p="+params;
            console.log("url::"+url);
            sendCmd('qrcode','enable', url, clientDetial,()=> {
            })
          } else {
            //关闭二维码
            sendCmd('qrcode','disable', clientDetial, ()=> {
            })
          }
        }
      })
    },
    changeSelectTerRowMethods(row) {
      this.perAddSelectTer = [...row]
    },
    addNewTer() {
      this.addTerModal = true
    },
    getGroupList() {
      service.getGroupList({page: 1,pageSize: 200000000}).then((res) => {
        this.groupList = [...res.data.records]

        this.getList()
      })
    },
    searchMethods() {

    },
    confirmUploadFile() {
      if(!this.clickCache.ip) {
        console.warn('没有找到对应的终端ip ---', this.clickCache)
      }
      const params = {
        ...this.terForm,
        mac: this.clickCache.mac,
        ip: this.clickCache.ip
      }

      service.clientEdit(params).then(() => {
        this.$message.success('修改成功')
        this.getList()
        this.handleClose()
      })
    },
    handleClose() {
      this.showTerDialog = false
      this.addTerModal = false
    },
    closeWindows() {
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择删除的终端')
        return
      }
      this.mutiDelList.forEach((item) => {
        this.closeWindow(item)
      })
    },
    closeWindow(row) {
      console.log("button:::",row)
      let instruct = {"system":"control","cmd":"shutdown"};
      let obj = {
        instruct: JSON.stringify(instruct),
        address: row.ip,
        port: 9191,
        size: 10240
      }
      service.instructSendWithIp(obj).then(() => {
        this.$message.success('操作成功')
        this.getList()
      })

    },
    changeDesktops(type) {
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择删除的终端')
        return
      }
      this.mutiDelList.forEach((item) => {
        this.changeDesktop(item, type)
      })
    },
    changeDesktop(row, type) {
      if(type === 'application') {
        let instruct = {"system":"control","cmd":"maxWin"};
        let obj = {
          instruct: JSON.stringify(instruct),
          address: row.ip,
          port: 9191,
          size: 10240
        }
        service.instructSendWithIp(obj).then((res) => {
          callback(res.data)
        }).catch(() => {
          // 错误处理
        })
      } else {
        let instruct = {"system":"control","cmd":"minWin"};
        let obj = {
          instruct: JSON.stringify(instruct),
          address: row.ip,
          port: 9191,
          size: 10240
        }
        service.instructSendWithIp(obj).then((res) => {
          callback(res.data)
        }).catch(() => {
          // 错误处理
        })
      }
    },
    startWindows() {
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择删除的终端')
        return
      }
      this.mutiDelList.forEach((item) => {
        this.startWindow(item)
      })
    },
    startWindow(row) {
      console.log("button:::",row)
      let obj = {
        "ip": row.ip,
        "mac": row.mac
      }
      service.wakeup(obj).then(() => {
        this.$message.success('操作成功')
        this.getList()
      })
    },
    restartWindows() {
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择删除的终端')
        return
      }
      this.mutiDelList.forEach((item) => {
        this.restartWindow(item)
      })
    },
    restartWindow(row) {
      console.log("button:::",row)
      let instruct = {"system":"control","cmd":"restart"};
      let obj = {
        instruct: JSON.stringify(instruct),
        address: row.ip,
        port: 9191,
        size: 10240
      }
      service.instructSendWithIp(obj).then(() => {
        this.$message.success('操作成功')
        this.getList()
      })
    },
    remoteControl(row) {
      // let location = window.location + "";
      // let head = location.split("/")[0];
      // let url =  head + "/jzkc/terminal/terminalDetail?id="+row.id+"&isFullScreen=true";
      // window.open(url);
      this.$router.push({ path: '/terminal/terminalDetail', query: { id: row.id, isFullScreen: true },meta: { keepAlive: false }})
    },
    goToFilePage(row) {
      this.$router.push(`/terminal/fileList?terminalId=${row.id}`)
    },
    restartCom() {
      // alert(111)

    },
    queryMethods() {
      this.searchObj.page = 1
      this.getList()
    },
    mutiDelMethods() {
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择删除的终端')
        return
      }
      this.statusProp = true
    },
    changeRowMethods(row) {
      this.mutiDelList = [...row]
    },
    delTerRow(row) {
      this.clickCache = Object.assign({}, row)
      this.statusProp = true
    },
    editTerInfo(row) {
      this.clickCache = {...row}
      Object.keys(this.terForm).forEach((fields) => {
        this.terForm[fields] = row[fields]
      })

      this.terForm.groupId = row.group_id
      this.terForm.id = row.id
      this.showTerDialog = true
    },
    cancelHandler() {
      this.statusProp = false
      this.clickCache = {}
      this.mutiDelList = []
    },
    confirmDelMethods() {
      if(this.mutiDelList.length > 0) {
        const params = {
          ids: []
        }
        this.mutiDelList.forEach((item) => {
          params.ids.push(item.id)
        })

        service.clientMutiDelete(params.ids).then(() => {
          this.$message.success('删除成功')
          this.getList()
          this.statusProp = false
          this.mutiDelList = []
          this.$refs.terminalTableRef.clearSelectionMethods()
        })
      } else {
        const params = {
          id: this.clickCache.id
        }
        service.clientDelete(params).then(() => {
          this.$message.success('删除成功')
          this.getList()
          this.statusProp = false
          this.clickCache = {}
        })
      }
    },
    getList() {
      const params = Object.assign({}, this.searchObj)
      this.$refs.terminalTableRef.queryData(params, () => {
        this.$refs.terminalTableRef.dataList.forEach((item) => {
          console.log('item ---', item)
          if(item.group_id) {
            const findIndex = this.groupList.findIndex((result) => {
              return item.group_id == result.id
            })
            if(findIndex !== -1) {
              item.group_name = this.groupList[findIndex].group_name
            }
          }
        })
        this.$refs.terminalTableRef.dataList.splice(0, 0)
      })
    },
    handleSizeChange() {

    },
    handleCurrentChange() {

    }
  }
}
</script>

<style scoped lang="scss">
  .terminal-page{
    padding: 15px;
    background: white;

    .commonTable{
      margin-top: 15px;
    }

    .page-nation{
      margin-top: 15px;
    }
  }

  .icon-image{
    width: .4rem;
    height: .4rem;
    position: relative;
    left: 8px;
    cursor: pointer;
    vertical-align: middle;
  }
  .icon-image-inside{
    width: 20px;
    height: 20px;
    margin-right: 15px;
  }
  .menu-list{
    .menu-list-row{
      padding: 10px;
      display: flex;
      align-items: center;
      cursor: pointer;

      &:hover {
        background-color: rgba(0,0,0,0.05);
      }
    }
  }
</style>
